/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.security.service.impl;

import org.apache.shiro.authc.credential.PasswordService;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.vacoor.nothing.security.entity.User;
import org.vacoor.nothing.security.service.UserService;
import org.vacoor.nothing.web.service.ServiceException;
import org.vacoor.nothing.web.service.support.CrudServiceImpl;

import java.util.List;
import java.util.Map;

/**
 * @author vacoor
 */
@Service
public class IUserService extends CrudServiceImpl<User, String> implements UserService {
    private static final String DEFAULT_SUPER_ADMIN_USERNAME = "root";
    private static final String DEFAULT_PASSWORD = "123456";

    private String superAdminUsername = DEFAULT_SUPER_ADMIN_USERNAME;
    @Autowired
    private PasswordService passwordService;

    public User findByUsername(String username) {
        User u = findOne("username", username);
        return u;
    }

    @Override
    public boolean isSuperAdmin(String username) {
        return superAdminUsername.equalsIgnoreCase(username);
    }

    @Override
    public User find(String id) {
        User u = super.find(id);
        Hibernate.initialize(u.getRoles());
        return u;
    }

    @Override
    public List<User> findMany(Map<String, Object> params) {
        List<User> users = super.findMany(params);
        for (User user : users) {
            Hibernate.initialize(user.getRoles());
        }
        return users;
    }

    @Override
    public void save(User user) {
        if (0 < count("username", user.getUsername())) {
            throw new ServiceException("username is exists");
        }
        String password = user.getPassword();
        password = StringUtils.hasLength(password) ? password : DEFAULT_PASSWORD;
        password = passwordService.encryptPassword(password);
        user.setPassword(password);
        super.save(user);
    }
}
